<!--
  智慧社区管理系统 - 维修服务
  @author Wu.Liang
  @date 2024-12-21
-->
<template>
  <div class="repair-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-actions">
        <el-button type="primary" @click="createDialogVisible = true" :loading="creating" :disabled="!canCreateOrder">
          <el-icon><Plus /></el-icon>
          创建工单
        </el-button>

      </div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="社区">
          <el-select
            v-model="searchForm.communityId"
            placeholder="请选择社区"
            clearable
            style="width: 200px"
            @change="handleCommunityChange"
          >
            <el-option
              v-for="item in communityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待受理" :value="1" />
            <el-option label="已受理" :value="2" />
            <el-option label="维修中" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已取消" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急程度">
          <el-select
            v-model="searchForm.urgencyLevel"
            placeholder="请选择紧急程度"
            clearable
            style="width: 150px"
          >
            <el-option label="紧急" :value="1" />
            <el-option label="一般" :value="2" />
            <el-option label="不紧急" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="工单号/维修内容/地址"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="table-title">
          <span>维修工单列表</span>
          <el-tag type="info" class="count-tag">共 {{ total }} 条记录</el-tag>
        </div>
        <div class="table-actions">
          <el-button
            type="danger"
            :disabled="!selectedRows.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="工单号" width="180" />
        <el-table-column prop="title" label="维修标题" width="200" show-overflow-tooltip />
        <el-table-column prop="communityName" label="社区" width="120" />
        <el-table-column prop="repairAddress" label="维修地址" width="200" show-overflow-tooltip />
        <el-table-column prop="description" label="维修内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="repairType" label="维修类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getRepairTypeTagType(row.repairType)">
              {{ getRepairTypeText(row.repairType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="urgencyLevel" label="紧急程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(getUrgencyType(row.urgencyLevel))">
              {{ getUrgencyText(row.urgencyLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="工单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(getStatusType(row.status))">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="申请人" width="100" />
        <el-table-column prop="repairmanName" label="维修人员" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="assignTime" label="分配时间" width="160" />
        <el-table-column prop="completeTime" label="完成时间" width="160" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button
              v-if="row.status === 1"
              type="warning"
              size="small"
              @click="handleAssign(row)"
            >
              分配
            </el-button>
            <el-button
              v-if="row.status === 2"
              type="info"
              size="small"
              @click="handleStartRepair(row)"
            >
              开始维修
            </el-button>
            <el-button
              v-if="row.status === 3"
              type="success"
              size="small"
              @click="handleComplete(row)"
            >
              完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建工单弹窗 -->
    <CreateOrderDialog
      v-model="createDialogVisible"
      :community-list="communityList"
      @confirm="handleCreateConfirm"
    />

    <!-- 工单详情弹窗 -->
    <RepairOrderDetailDialog
      v-model="detailDialogVisible"
      :repair-order="currentOrder"
      @assign="handleAssign"
      @complete="handleComplete"
    />

    <!-- 分配弹窗 -->
    <AssignDialog
      v-model="assignDialogVisible"
      :repair-order="currentOrder"
      :loading="assigning"
      @confirm="handleAssignConfirm"
    />

    <!-- 完成工单弹窗 -->
    <CompleteDialog
      v-model="completeDialogVisible"
      :repair-order="currentOrder"
      :loading="completing"
      @confirm="handleCompleteConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Plus, User, Download, Search, Refresh } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { isSuperAdminOrPropertyCompany } from '@/utils/permission'
import { showMessage } from '@/utils/message'
import { repairOrderApi } from '@/api/repair'
import { communityApi } from '@/api/community'
import CreateOrderDialog from './components/CreateOrderDialog.vue'
import RepairOrderDetailDialog from './components/RepairOrderDetailDialog.vue'
import AssignDialog from './components/AssignDialog.vue'
import CompleteDialog from './components/CompleteDialog.vue'

// 作者: Wu.Liang

// 用户状态
const userStore = useUserStore()

// 权限检查
const isSuperAdmin = computed(() => userStore.isSuperAdmin)
const hasPropertyCompany = computed(() => userStore.hasPropertyCompany)

// 创建工单权限检查
const canCreateOrder = computed(() => {
  const result = isSuperAdmin.value || hasPropertyCompany.value
  console.log('创建工单按钮权限检查:', {
    isSuperAdmin: isSuperAdmin.value,
    hasPropertyCompany: hasPropertyCompany.value,
    canCreateOrder: result,
    userRoles: userStore.userRoles,
    userInfo: userStore.userInfo
  })
  return result
})

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const assigning = ref(false)
const completing = ref(false)

// 表格数据 - 确保初始化为数组
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])
const total = ref(0)

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20
})

// 搜索表单
const searchForm = reactive({
  communityId: undefined,
  status: undefined,
  urgencyLevel: undefined,
  startDate: undefined,
  endDate: undefined,
  keyword: undefined
})

// 日期范围
const dateRange = ref(null)

// 社区列表加载逻辑
const communityList = ref<{id:number,name:string}[]>([])

const loadCommunityList = async () => {
  try {
    // 使用标准的社区列表接口，后端通过数据权限自动过滤
    // 超级管理员：看到全部社区
    // 物业公司人员：只看到关联的社区
    // 普通用户：看到空列表
    const response = await communityApi.getCommunityList({})
    communityList.value = Array.isArray(response.data)
      ? response.data.map((item:any) => ({ 
          id: item.id, 
          name: item.communityName || item.name 
        }))
      : []
  } catch (error) {
    console.error('加载社区列表失败:', error)
    communityList.value = []
  }
}

// 弹窗控制
const createDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const assignDialogVisible = ref(false)
const completeDialogVisible = ref(false)

// 当前操作的工单
const currentOrder = ref(null)

// 计算属性
const queryParams = computed(() => ({
  ...searchForm,
  current: pagination.current,
  size: pagination.size
}))

// 批量分配权限检查
const canBatchAssign = computed(() => {
  return isSuperAdminOrPropertyCompany()
})

// 生命周期
onMounted(() => {
  loadData()
  loadCommunityList()
})

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const response = await repairOrderApi.getRepairOrderList(queryParams.value)
    if (response.success) {
      // 确保数据是数组格式
      tableData.value = Array.isArray(response.data?.records) ? response.data.records : []
      total.value = response.data?.total || 0
      
      // 调试信息：输出每个工单的状态值
      console.log('维修工单列表数据:', tableData.value.map(item => ({
        id: item.id,
        orderNo: item.orderNo,
        title: item.title,
        status: item.status,
        statusType: typeof item.status,
        statusName: getStatusText(item.status)
      })))
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载维修工单数据失败:', error)
    showMessage({ type: 'error', message: '加载数据失败' })
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 事件处理
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    communityId: undefined,
    status: undefined,
    urgencyLevel: undefined,
    startDate: undefined,
    endDate: undefined,
    keyword: undefined
  })
  dateRange.value = null
  pagination.current = 1
  loadData()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

const handleCommunityChange = (communityId: number) => {
  // 社区变化时的处理逻辑
}

const handleDateRangeChange = (range: [string, string] | null) => {
  if (range) {
    searchForm.startDate = range[0]
    searchForm.endDate = range[1]
  } else {
    searchForm.startDate = undefined
    searchForm.endDate = undefined
  }
}

// 创建工单
const handleCreateOrder = () => {
  // 重置表单
  createForm.value = {
    title: '',
    description: '',
    householdAddress: '',
    contactPhone: '',
    contactName: '',
    priority: 2, // 默认中等优先级
    category: '',
    expectedTime: ''
  }
  createDialogVisible.value = true
}

// 创建工单确认
const handleCreateConfirm = async (data: any) => {
  try {
    creating.value = true
    const response = await repairOrderApi.createRepairOrder(data)
    if (response && response.code === 200) {
      showMessage({ type: 'success', message: '工单创建成功' })
      createDialogVisible.value = false
      loadData()
    } else {
      showMessage({ type: 'error', message: response.message || '工单创建失败' })
    }
  } catch (error) {
    showMessage({ type: 'error', message: '工单创建失败' })
  } finally {
    creating.value = false
  }
}

// 查看详情
const handleViewDetail = async (row: any) => {
  try {
    currentOrder.value = row
    detailDialogVisible.value = true
  } catch (error) {
    console.error('查看详情失败:', error)
    showMessage({ type: 'error', message: '查看详情失败' })
  }
}

// 分配工单
const handleAssign = (row: any) => {
  currentOrder.value = row
  assignDialogVisible.value = true
}

// 分配确认
const handleAssignConfirm = async (data: any) => {
  try {
    assigning.value = true
    const response = await repairOrderApi.assignRepairOrder(currentOrder.value.id, data)
    if (response.success) {
      showMessage({ type: 'success', message: '工单分配成功' })
      assignDialogVisible.value = false
      detailDialogVisible.value = false // 关闭详情页
      loadData()
    } else {
      showMessage({ type: 'error', message: response.message || '工单分配失败' })
    }
  } catch (error) {
    console.error('分配工单失败:', error)
    showMessage({ type: 'error', message: '分配工单失败' })
  } finally {
    assigning.value = false
  }
}

// 开始维修
const handleStartRepair = async (row: any) => {
  try {
    const response = await repairOrderApi.updateRepairOrderStatus(row.id, 3, '开始维修')
    if (response.success) {
      showMessage({ type: 'success', message: '已开始维修' })
      loadData()
    }
  } catch (error) {
    console.error('开始维修失败:', error)
    showMessage({ type: 'error', message: '开始维修失败' })
  }
}

// 完成工单
const handleComplete = (row: any) => {
  currentOrder.value = row
  completeDialogVisible.value = true
}

// 完成确认
const handleCompleteConfirm = async (data: any) => {
  try {
    completing.value = true
    const response = await repairOrderApi.completeRepairOrder(currentOrder.value.id, data)
    if (response.success) {
      showMessage({ type: 'success', message: '工单完成成功' })
      completeDialogVisible.value = false
      detailDialogVisible.value = false // 关闭详情页
      loadData()
    } else {
      showMessage({ type: 'error', message: response.message || '工单完成失败' })
    }
  } catch (error) {
    console.error('完成工单失败:', error)
    showMessage({ type: 'error', message: '完成工单失败' })
  } finally {
    completing.value = false
  }
}

// 取消工单
const handleCancel = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个工单吗？',
      '取消确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await repairOrderApi.cancelRepairOrder(row.id, '管理员取消')
    if (response.success) {
      showMessage({ type: 'success', message: '工单已取消' })
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消工单失败:', error)
      showMessage({ type: 'error', message: '取消工单失败' })
    }
  }
}

// 批量分配
const handleBatchAssign = async () => {
  if (!selectedRows.value.length) {
    showMessage({ type: 'warning', message: '请选择要分配的工单' })
    return
  }

  showMessage({ type: 'info', message: '批量分配功能待实现' })
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) {
    showMessage({ type: 'warning', message: '请选择要删除的工单' })
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条维修工单吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 获取选中的ID列表
    const ids = selectedRows.value.map(row => row.id)
    
    // 调用批量删除API
    const response = await repairOrderApi.batchDeleteRepairOrders(ids)
    
    if (response.success) {
      showMessage({ type: 'success', message: '批量删除成功' })
      // 清空选中状态
      selectedRows.value = []
      // 刷新列表
      await loadData()
    } else {
      showMessage({ type: 'error', message: response.message || '批量删除失败' })
    }
  } catch (error: any) {
    if (error === 'cancel') return
    console.error('批量删除失败:', error)
    showMessage({ type: 'error', message: error.message || '批量删除失败' })
  }
}

// 导出数据
const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = ElLoading.service({
      lock: true,
      text: '正在导出数据...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 构建导出参数
    const exportParams = {
      ...searchForm,
      pageSize: 10000, // 导出时获取更多数据
      pageNum: 1
    }
    
    // 调用导出API
    const response = await repairOrderApi.exportRepairOrders(exportParams)
    
    if (response.success && response.data) {
      // 创建下载链接
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `维修工单_${new Date().toISOString().slice(0, 10)}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      showMessage({ type: 'success', message: '导出成功，文件已下载' })
    } else {
      showMessage({ type: 'error', message: response.message || '导出失败' })
    }
  } catch (error: any) {
    console.error('导出失败:', error)
    showMessage({ type: 'error', message: error.message || '导出失败' })
  } finally {
    // 关闭加载状态
    ElLoading.service().close()
  }
}

// 工具函数
const getStatusType = (status: number) => {
  const statusMap: Record<number, string> = {
    1: 'warning',
    2: 'info',
    3: 'primary',
    4: 'success',
    5: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '待受理',
    2: '已受理',
    3: '维修中',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || '未知'
}

const getUrgencyType = (urgencyLevel: number) => {
  const urgencyMap: Record<number, string> = {
    1: 'danger',
    2: 'warning',
    3: 'info'
  }
  return urgencyMap[urgencyLevel] || 'info'
}

const getUrgencyText = (urgencyLevel: number) => {
  const urgencyMap: Record<number, string> = {
    1: '紧急',
    2: '一般',
    3: '不紧急'
  }
  return urgencyMap[urgencyLevel] || '未知'
}

const getRepairTypeTagType = (repairType: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'danger',
    5: 'info'
  }
  return typeMap[repairType] || 'info'
}

const getRepairTypeText = (repairType: number) => {
  const typeMap: Record<number, string> = {
    1: '水电',
    2: '门窗',
    3: '电梯',
    4: '消防',
    5: '其他'
  }
  return typeMap[repairType] || '未知'
}

const getTagType = (type: string) => {
  return type || 'info'
}
</script>

<style lang="scss" scoped>
.repair-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
  }

  .page-actions {
    display: flex;
    gap: 10px;
  }
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .table-title {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 16px;
      font-weight: 600;
      color: #303133;

      .count-tag {
        font-size: 12px;
      }
    }

    .table-actions {
      display: flex;
      gap: 10px;
    }
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
